/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.molyfun.parents.im;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.molyfun.parents.R;
import com.molyfun.parents.im.model.ChatMessageEntity;
import com.molyfun.parents.im.model.NormalFileMessageBody;

/**
 * 语音row播放点击事件监听
 *
 */
public class ChatRowVoicePlayClickListener implements View.OnClickListener {
	private static final String TAG = "VoicePlayClickListener";
	ChatMessageEntity message;
	NormalFileMessageBody voiceBody;
	ImageView voiceIconView;

	private AnimationDrawable voiceAnimation = null;
	MediaPlayer mediaPlayer = null;
	Activity activity;
	private ChatType chatType;
	private BaseAdapter adapter;

	public static boolean isPlaying = false;
	public static ChatRowVoicePlayClickListener currentPlayListener = null;
	public static String playMsgId;

	public ChatRowVoicePlayClickListener(ChatMessageEntity message, ImageView v, BaseAdapter adapter, Activity context) {
		this.message = message;
		voiceBody = message.getBody();
		this.adapter = adapter;
		voiceIconView = v;
		this.activity = context;
	}

	public void stopPlayVoice() {
		voiceAnimation.stop();
		if(message.isUseNative()){
			voiceIconView.setImageResource(R.drawable.ease_chatto_voice_playing);
		}else{
			if (message.direct() == EMMessage.Direct.RECEIVE) {
				voiceIconView.setImageResource(R.drawable.ease_chatfrom_voice_playing);
			} else {
				voiceIconView.setImageResource(R.drawable.ease_chatto_voice_playing);
			}
		}

		// stop play voice
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
		}
		isPlaying = false;
		playMsgId = null;
		adapter.notifyDataSetChanged();
	}

	public void playVoice(String filePath) {
//		if (!(new File(filePath).exists())) {
//			return;
//		}
		playMsgId = message.getId();
		AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);

		mediaPlayer = new MediaPlayer();
//		if (EaseUI.getInstance().getSettingsProvider().isSpeakerOpened()) {
//			audioManager.setMode(AudioManager.MODE_NORMAL);
//			audioManager.setSpeakerphoneOn(true);
//			mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
//		} else {
//			audioManager.setSpeakerphoneOn(false);// 关闭扬声器
//			// 把声音设定成Earpiece（听筒）出来，设定为正在通话中
//			audioManager.setMode(AudioManager.MODE_IN_CALL);
//			mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
//		}
		try {
			mediaPlayer.setDataSource(filePath);
			mediaPlayer.prepare();
			mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					// TODO Auto-generated method stub
					mediaPlayer.release();
					mediaPlayer = null;
					stopPlayVoice(); // stop animation
				}

			});
			isPlaying = true;
			currentPlayListener = this;
			mediaPlayer.start();
			showAnimation();

		} catch (Exception e) {
		    System.out.println();
		}
	}

	// show the voice playing animation
	private void showAnimation() {
		// play voice, and start animation
		if(message.isUseNative()){
			voiceIconView.setImageResource(R.drawable.voice_to_icon);
		}else{
			if (message.direct() == EMMessage.Direct.RECEIVE) {
				voiceIconView.setImageResource(R.drawable.voice_from_icon);
			} else {
				voiceIconView.setImageResource(R.drawable.voice_to_icon);
			}
		}

		voiceAnimation = (AnimationDrawable) voiceIconView.getDrawable();
		voiceAnimation.start();
	}

	@Override
	public void onClick(View v) {
		String st = activity.getResources().getString(R.string.Is_download_voice_click_later);
		if (isPlaying) {
			if (playMsgId != null && playMsgId.equals(message.getId())) {
				currentPlayListener.stopPlayVoice();
				return;
			}
			currentPlayListener.stopPlayVoice();
		}

//		if (message.direct() == EMMessage.Direct.SEND) {
//			// for sent msg, we will try to play the voice file directly
//			playVoice(voiceBody.getLocalUrl());
//		} else {

		if(message.isUseNative()){
			ChatMessageEntity.ErrorNativeBody errorNativeBody = message.getErrorNativeBody();
			playVoice(errorNativeBody.getFilePath());
		}else{
			playVoice(voiceBody.getRemoteUrl());
		}
//		}
	}
}
